let isRecording = false;
let recordedData = [];
let urlFilter = '';
let urlBlacklist = [];

// 更改图标状态
function updateIcon(recording) {
  const iconPrefix = recording ? 'recording' : 'record';
  chrome.action.setIcon({
    path: {
      16: `icons/${iconPrefix}_16.png`,
      32: `icons/${iconPrefix}_32.png`,
      48: `icons/${iconPrefix}_48.png`,
      128: `icons/${iconPrefix}_128.png`
    }
  });
}

// 更详细的判断URL过滤条件
function matchesUrlFilter(url) {
  if (!urlFilter || urlFilter.trim() === '') {
    console.log(`[API录制器] URL过滤为空，允许所有URL: ${url}`);
    return true;
  }
  
  const matches = url.includes(urlFilter);
  console.log(`[API录制器] URL过滤 "${urlFilter}" ${matches ? '匹配' : '不匹配'} URL: ${url}`);
  return matches;
}

// 更详细的判断URL黑名单
function matchesUrlBlacklist(url) {
  // 如果黑名单为空，直接返回false
  if (!urlBlacklist || urlBlacklist.length === 0) {
    console.log(`[API录制器] 黑名单为空，不排除任何URL`);
    return false;
  }
  
  // 遍历黑名单项
  for (const blacklistItem of urlBlacklist) {
    if (blacklistItem && url.includes(blacklistItem)) {
      console.log(`[API录制器] URL匹配黑名单项"${blacklistItem}", 不录制: ${url}`);
      return true;
    }
  }
  
  console.log(`[API录制器] URL不在黑名单中，允许录制: ${url}`);
  return false;
}

// 提取URL路径（不含域名和参数）
function extractUrlPath(fullUrl) {
  try {
    const url = new URL(fullUrl);
    return url.pathname;
  } catch (e) {
    return fullUrl;
  }
}

// 加载设置
chrome.storage.local.get(['urlFilter', 'urlBlacklist'], (result) => {
  if (result.urlFilter) urlFilter = result.urlFilter;
  if (result.urlBlacklist) {
    try {
      urlBlacklist = result.urlBlacklist.split('\n').filter(line => line.trim() !== '');
    } catch (e) {
      console.error('解析URL黑名单时出错:', e);
    }
  }
});

// 监听网络请求
chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
    if (!isRecording) {
      console.log(`[API录制器] 未录制: 录制未开启`);
      return { cancel: false };
    }
    
    // 只处理POST请求
    if (details.method !== 'POST') {
      console.log(`[API录制器] 未录制: 非POST请求 - ${details.method}`);
      return { cancel: false };
    }
    
    const url = details.url;
    console.log(`[API录制器] 检查POST请求: ${url}`);
    
    // 先检查URL过滤
    if (!matchesUrlFilter(url)) {
      console.log(`[API录制器] 未录制: URL不匹配过滤条件 "${urlFilter}"`);
      return { cancel: false };
    }
    
    // 再检查URL黑名单
    if (matchesUrlBlacklist(url)) {
      console.log(`[API录制器] 未录制: URL匹配黑名单项`);
      return { cancel: false };
    }
    
    console.log(`[API录制器] 录制POST请求: ${url}`);
    
    const timestamp = new Date().toISOString();
    const id = `request_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    // 提取请求体（如果存在）
    let requestBody = '无请求数据';
    if (details.requestBody) {
      if (details.requestBody.raw) {
        // 处理原始请求体
        try {
          const decoder = new TextDecoder('utf-8');
          const rawData = details.requestBody.raw[0].bytes;
          requestBody = decoder.decode(rawData);
          
          // 尝试格式化JSON
          try {
            const jsonData = JSON.parse(requestBody);
            requestBody = JSON.stringify(jsonData, null, 2);
          } catch (e) {
            // 不是JSON，保持原样
          }
        } catch (e) {
          requestBody = '无法解析的二进制数据';
        }
      } else if (details.requestBody.formData) {
        // 处理表单数据
        requestBody = JSON.stringify(details.requestBody.formData, null, 2);
      }
    }
    
    // 创建记录对象
    const record = {
      id,
      timestamp,
      fullUrl: details.url,
      url: extractUrlPath(details.url),
      method: 'POST',
      requestBody: requestBody,
      responseBody: '等待响应...'
    };
    
    // 添加到记录列表
    recordedData.push(record);
    
    // 通知popup更新
    try {
      chrome.runtime.sendMessage({ type: 'updateResults', data: recordedData });
    } catch (e) {
      // 忽略错误，可能popup未打开
    }
    
    return { cancel: false };
  },
  { urls: ["<all_urls>"] },
  ["requestBody"]  // 显式指定要捕获请求体
);

// 监听响应体
chrome.webRequest.onCompleted.addListener(
  (details) => {
    if (!isRecording) return;
    
    // 只处理POST请求
    if (details.method !== 'POST') return;
    
    // 查找匹配的请求记录
    const record = recordedData.find(r => r.fullUrl === details.url);
    if (record) {
      // 注意：这里无法直接获取responseBody，需要使用devtools.network API
      // 或者使用content script注入和拦截XHR/fetch请求
      // 简单起见，我们在这里只记录状态码
      record.statusCode = details.statusCode;
    }
  },
  { urls: ["<all_urls>"] }
);

// 处理消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  try {
    console.log(`[API录制器] 收到消息:`, message.type);
    
    // 获取录制状态
    if (message.type === 'getRecordingState') {
      sendResponse({
        isRecording: isRecording,
        data: recordedData
      });
    }
    
    // 开始录制
    else if (message.type === 'startRecording') {
      console.log('[API录制器] 开始录制, 同步更新设置...');

      // 从消息中直接获取设置
      urlFilter = message.urlFilter || '';
      
      try {
        // 确保黑名单被正确处理为数组
        if (message.urlBlacklist) {
          urlBlacklist = message.urlBlacklist
            .split('\n')
            .filter(line => line.trim() !== '')
            .map(line => line.trim());
        } else {
          urlBlacklist = [];
        }
      } catch (e) {
        console.error('[API录制器] 处理黑名单时出错:', e);
        urlBlacklist = [];
      }
      
      // 详细输出当前黑名单内容
      console.log(`[API录制器] 当前URL过滤器: "${urlFilter}"`);
      console.log(`[API录制器] 当前黑名单项数: ${urlBlacklist.length}`);
      if (urlBlacklist.length > 0) {
        console.log(`[API录制器] 黑名单内容:`, urlBlacklist);
      }

      // 保存设置以便持久化
      chrome.storage.local.set({
        urlFilter: urlFilter,
        urlBlacklist: message.urlBlacklist || ''
      });
      
      isRecording = true;
      updateIcon(true);
      sendResponse({ success: true });
    }
    
    // 停止录制
    else if (message.type === 'stopRecording') {
      isRecording = false;
      updateIcon(false);
      console.log('[API录制器] 停止录制');
      sendResponse({ success: true });
    }
    
    // 清空记录
    else if (message.type === 'clearRecords') {
      recordedData = [];
      console.log('[API录制器] 清空记录');
      sendResponse({ success: true, data: recordedData });
    }
    
    // 删除单条记录
    else if (message.type === 'deleteRecord') {
      recordedData = recordedData.filter(r => r.id !== message.id);
      console.log(`[API录制器] 删除记录: ${message.id}`);
      sendResponse({ success: true, data: recordedData });
    }
    
    // 更新设置
    else if (message.type === 'updateSettings') {
      const oldFilter = urlFilter;
      const oldBlacklistLength = urlBlacklist.length;
      
      urlFilter = message.urlFilter;
      try {
        urlBlacklist = message.urlBlacklist.split('\n')
          .filter(line => line.trim() !== '')
          .map(line => line.trim());
      } catch (e) {
        urlBlacklist = [];
        console.error('解析URL黑名单时出错:', e);
      }
      
      // 输出详细日志以方便调试
      console.log(`[API录制器] 更新设置: urlFilter从"${oldFilter}"改为"${urlFilter}"`);
      console.log(`[API录制器] 更新设置: urlBlacklist从${oldBlacklistLength}项改为${urlBlacklist.length}项`);
      console.log(`[API录制器] URL黑名单内容:`, urlBlacklist);
      
      // 保存设置到存储，确保设置持久化
      chrome.storage.local.set({ 
        urlFilter: urlFilter,
        urlBlacklist: message.urlBlacklist 
      });
      
      sendResponse({ success: true });
    }
    
    // 处理来自content script的请求体捕获
    else if (message.type === 'captureRequest') {
      const record = recordedData.find(r => r.fullUrl === message.url);
      if (record) {
        record.requestBody = message.requestBody || record.requestBody;
        
        // 通知popup更新
        try {
          chrome.runtime.sendMessage({ type: 'updateResults', data: recordedData });
        } catch (e) {
          // 忽略错误，可能popup未打开
        }
      } else {
        // 如果记录不存在，创建新记录
        const timestamp = new Date().toISOString();
        const id = `request_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        
        const newRecord = {
          id,
          timestamp,
          fullUrl: message.url,
          url: extractUrlPath(message.url),
          method: 'POST',
          requestBody: message.requestBody || '无请求数据',
          responseBody: '等待响应...'
        };
        
        recordedData.push(newRecord);
        console.log(`[API录制器] 创建新记录: ${id}`);
        
        // 通知popup更新
        try {
          chrome.runtime.sendMessage({ type: 'updateResults', data: recordedData });
        } catch (e) {
          // 忽略错误，可能popup未打开
        }
      }
      
      sendResponse({ success: true });
    }
    
    // 处理来自content script的响应体捕获
    else if (message.type === 'captureResponse') {
      const record = recordedData.find(r => r.fullUrl === message.url);
      if (record) {
        record.responseBody = message.responseBody;
        // 通知popup更新
        try {
          chrome.runtime.sendMessage({ type: 'updateResults', data: recordedData });
        } catch (e) {
          // 忽略错误，可能popup未打开
        }
      }
      
      sendResponse({ success: true });
    }
    
    // 添加处理devtools消息的处理程序
    else if (message.type === 'captureCompleteRequest') {
      console.log(`[API录制器] 收到完整请求捕获: ${message.url}`);
      
      // 查找或创建记录
      const existingRecord = recordedData.find(r => r.fullUrl === message.url);
      
      if (existingRecord) {
        // 更新已存在的记录
        existingRecord.requestBody = message.requestBody || existingRecord.requestBody;
        existingRecord.responseBody = message.responseBody;
        
        console.log(`[API录制器] 更新已存在记录: ${existingRecord.id}`);
      } else {
        // 创建新记录
        const timestamp = new Date().toISOString();
        const id = `request_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        
        const newRecord = {
          id,
          timestamp,
          fullUrl: message.url,
          url: extractUrlPath(message.url),
          method: 'POST',
          requestBody: message.requestBody || '无请求数据',
          responseBody: message.responseBody || '无响应数据'
        };
        
        recordedData.push(newRecord);
        console.log(`[API录制器] 创建新记录: ${id}`);
      }
      
      // 通知popup更新
      try {
        chrome.runtime.sendMessage({ type: 'updateResults', data: recordedData });
      } catch (e) {
        // 忽略错误，可能popup未打开
        console.log(`[API录制器] 无法通知popup: ${e.message}`);
      }
      
      sendResponse({ success: true });
    }
    
    // 处理获取单个记录的请求
    else if (message.type === 'getItemById') {
      const item = recordedData.find(r => r.id === message.id);
      console.log(`[API录制器] 获取记录: ${message.id}, 找到: ${!!item}`);
      sendResponse({ success: true, item });
    }
    
    // 处理未知消息类型
    else {
      console.warn('未知消息类型:', message.type);
      sendResponse({ success: false, error: '未知消息类型' });
    }
  } catch (error) {
    console.error('处理消息时出错:', error);
    sendResponse({ success: false, error: error.message });
  }
  
  return true; // 保持消息通道开放，支持异步响应
}); 